import { useCallback, useEffect, useRef, useState } from "react";
import { useRecoilValue } from "recoil";
import { getConversationList } from "../../../../api/conversation";
import { ConversationList } from "../../../../common/components/ConversationList";
import { ConversationWindows } from "../../../../common/components/ConversationWindows";
import { ConversationInfoItem, PermissionType } from "../../../../common/types/conversation";
import { useManagerIm } from "../../../../hooks/useManagerIm";
import { userInfoState } from "../../../../store/userInfo";
interface MyConversationProps {
  currentConversation?: ConversationInfoItem;
  handleChangeConversation: (conversation: ConversationInfoItem) => void;
}


export const MyConversation: React.FC<MyConversationProps> = (props) => {
  const { currentConversation, handleChangeConversation } = props;

  const [conversationInfo, setConversationInfo] = useState<Array<ConversationInfoItem>>([]);
  const conversationRef = useRef<any>(currentConversation);
  const managerIm = useManagerIm();
  const userInfo = useRecoilValue(userInfoState);


  const initConversationInfo = useCallback(async (conversation?: ConversationInfoItem) => {
    const result = await getConversationList();
    const { data } = result;
    const { conversation_list } = data;
    const my_conversation_list = conversation_list.filter((item: any) => {
      return item.staff_id === userInfo.id
    })
    my_conversation_list && setConversationInfo(my_conversation_list);
    my_conversation_list && handleChangeConversation(conversation || my_conversation_list[0]);
  }, [currentConversation]);


  useEffect(() => {
    initConversationInfo();
  }, [localStorage.getItem('token')]);

  useEffect(() => {
    conversationRef.current = currentConversation;
  }, [currentConversation])

  useEffect(() => {
    if (userInfo.id) {
      managerIm.on('manager', async (data: { type: number; }) => {
        if (data.type === 1) { // 有新的工单来了，需要更新列表
          if (!(userInfo.permission === PermissionType.customer)) {
            await initConversationInfo(conversationRef.current);
          }
        }
      })

      managerIm.on(`manager_${userInfo.id}`, async (data: any) => {
        const { type, conversation } = data;
        if (type === 2) {
          await initConversationInfo(conversation);
        }
      })
    }

  }, [userInfo]);

  return (<div className='all-conversation-wrapper'>
    <div className='all-conversation-sider'>
      <ConversationList
        currentConversation={currentConversation}
        handleChangeConversation={handleChangeConversation}
        data={conversationInfo} />
    </div>
    {currentConversation ?
      <div className='all-conversation-content'><ConversationWindows initConversationInfo={initConversationInfo} currentConversation={currentConversation} /></div>
      : null}
  </div>)
}